package com.sanyue.dualPointer;

import org.junit.Test;

/**
 * @author sanyue
 * @version 1.0
 * @description: TODO
 * @date 2022/3/15 上午10:16
 * 接雨水
 */
public class Rain {

    @Test
    public void testTrap() {
        int[] height = {0, 1, 0, 2, 1, 0, 1, 3, 2, 1, 2, 1};
        int ans = trap(height);
        System.out.println("ans:" + ans);
    }

    public int trap(int[] height) {
        int n = height.length;
        int[] l = new int[n]; // l[i]表示i左边的最大高度
        int[] r = new int[n]; // r[i]表示i右边的最大高度
        for (int i = 1; i < n; i++) {
            l[i] = Math.max(height[i - 1], l[i - 1]);
        }
        for (int i = n - 2; i >= 0; i--) {
            r[i] = Math.max(height[i + 1], r[i + 1]);
        }
        int ans = 0;
        for (int i = 0; i < n; i++) {
            if (l[i] > height[i] && r[i] > height[i]) ans += Math.min(l[i], r[i]) - height[i];
        }
        return ans;
    }
}